package com.qqtech.qquan.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.enums.SysMenuStatusDictEnum;
import com.qqtech.qquan.sys.model.SysMenu;
import com.qqtech.qquan.sys.model.SysMenuQuery;
import com.qqtech.qquan.sys.model.SysMenuVo;
import com.qqtech.qquan.sys.model.SysRole;
import com.qqtech.qquan.sys.service.SysMenuService;
import com.qqtech.qquan.sys.service.SysRoleService;
import com.qqtech.qquan.user.model.UserAdmin;
import com.qqtech.qquan.user.service.UserAdminService;

@Controller
@RequestMapping(value = "/sys/menu")
public class SysMenuController extends BaseAgentController {
	@Resource
	private SysMenuService sysMenuService;
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private UserAdminService userAdminService;

	@Override
	protected BaseService<SysMenu> getBaseService() {
		return sysMenuService;
	}

	/**
	 * 登录加载左边的子菜单
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/leftmenu/{menuId}", method = RequestMethod.POST)
	public Result leftmenu(@PathVariable String menuId, HttpServletRequest request, HttpServletResponse response) {
		SysMenuQuery sysMenu = new SysMenuQuery();
		sysMenu.setParentId(menuId);
		sysMenu.setStatus(SysMenuStatusDictEnum.ENABLE.getCode());
		List<SysMenuVo> list = null;
		UserAdmin login = super.getLoginUser();
		UserAdmin user = userAdminService.getOne(login);
		List<SysRole> roles = sysRoleService.queryListByUserId(user.getId()); // 得到角色

		Boolean isAdmin = false;
		for (SysRole role : roles) {
			if (SysConst.SYS_ROLE_ADMIN_NAME.equals(role.getName())) {
				isAdmin = true;
			}
		}
		if (isAdmin) { // 总管理员
			list = sysMenuService.queryListByParentId(sysMenu);
		} else {
			List<Integer> roleIdList = new ArrayList<Integer>(roles.size());
			for (SysRole r : roles) {
				roleIdList.add(r.getId());
			}
			sysMenu.setRoleIdList(roleIdList);
			list = sysMenuService.menuForRole(sysMenu);
		}
		List tree = new ArrayList();
		if (null != list) {
			for (int i = 0; i < list.size(); i++) {
				SysMenu m = (SysMenu) list.get(i);
				/*
				 * 去掉 if (login != null && "kefu".equals(login.getUserName())) {
				 * if (!(m.getName().indexOf("举报") > -1)) { continue; } }
				 */
				Map<Object, Object> node = new HashMap<Object, Object>();
				node.put("id", m.getMenuId());
				node.put("text", m.getName());
				if (m.getType() == 1) {
					node.put("state", "closed");
					if (StringUtils.isBlank(m.getIcon())) {
						node.put("iconCls", "icon-folder");
					} else {
						node.put("iconCls", m.getIcon());
					}
				} else {
					node.put("state", "open");
					if (StringUtils.isBlank(m.getIcon())) {
						node.put("iconCls", "icon-pict");
					} else {
						node.put("iconCls", m.getIcon());
					}
				}
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("parentId", m.getParentId());
				attributes.put("type", m.getType());
				attributes.put("url", request.getContextPath() + m.getUrl());
				node.put("attributes", attributes);
				tree.add(node);
			}
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/menu/menu-list";
	}

	/**
	 * 列表页面数据
	 * 
	 * @param userDomain
	 *            查询条件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage doList(SysMenuQuery sysMenu, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();

		Pageable pageKit = new PageKit(sysMenu.getPage(), new PageOrder(Direction.ASC, "id"));
		Page<SysMenu> page = sysMenuService.queryPageList(sysMenu, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(page.getNumberOfElements());
		return adminPage;
	}

	@RequestMapping(value = "/tree", method = RequestMethod.POST)
	@ResponseBody
	public Result tree(HttpServletRequest request, HttpServletResponse response) {
		String parentId = request.getParameter("id");
		SysMenuQuery sysMenu = new SysMenuQuery();
		sysMenu.setParentId(parentId);
		List<SysMenuVo> list = sysMenuService.queryListByParentId(sysMenu);
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>();
		if (null != list) {
			for (int i = 0; i < list.size(); i++) {
				SysMenuVo m = (SysMenuVo) list.get(i);
				Map<Object, Object> node = new HashMap<Object, Object>();
				node.put("id", m.getMenuId());
				node.put("text", m.getName());
				if (m.getType() == 1) {
					node.put("state", "closed");
					node.put("iconCls", "icon-menu");
				} else {
					node.put("state", "open");
					node.put("iconCls", "icon-star");
				}
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("parentId", m.getParentId());
				attributes.put("type", m.getType());
				node.put("attributes", attributes);
				tree.add(node);
			}
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@RequestParam(required = false) String parentId, HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtil.isNotBlank(parentId)) {
			SysMenu parent = sysMenuService.getByMenuId(parentId);
			request.setAttribute("parent", parent);
		}
		return "/menu/menu-update";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(SysMenu menu, HttpServletRequest request, HttpServletResponse response) {
		UserAdmin login = getLoginUser(request, response);
		UserAdmin user = userAdminService.getOne(login);
		Result ret = new Result();
		if (StringUtils.isBlank(menu.getName())) {
			ret.addErr("请输入菜单姓名");
		}
		if (ret.checkForm()) {
			menu.setUserId(user.getId());
			if (menu.getType().intValue() == 1) {
				if (StringUtil.isBlank(menu.getIcon())) {
					menu.setIcon("icon-folder");
				}
			} else {
				if (StringUtil.isBlank(menu.getIcon())) {
					menu.setIcon("icon-pict");
				}
			}
			if (StringUtil.isBlank(menu.getParentId())) {
				menu.setParentId(null);
			}
			menu.setOrderIdx(Long.valueOf(sysMenuService.getMaxOrderIdx() + 1));
			String dateStr = new DateTime().toString("yyMMddHHmmssSSS");
			String rand = StringUtil.getRandomNum(3);
			menu.setNewAt(TimeUtil.now());
			menu.setUpdAt(TimeUtil.now());
			menu.setMenuId(dateStr + rand); // 菜单id
			sysMenuService.insert(menu);
		}
		return ret;
	}

	@RequestMapping(value = "/update/{menuId}", method = RequestMethod.GET)
	public String update(@PathVariable String menuId, HttpServletRequest request, HttpServletResponse response) {
		SysMenu menu = sysMenuService.getByMenuId(menuId);
		request.setAttribute("menu", menu);
		if (null != menu && null != menu.getParentId()) {
			SysMenu parent = sysMenuService.getByMenuId(menu.getParentId());
			request.setAttribute("parent", parent);
		}
		return "/menu/menu-update";
	}

	@RequestMapping(value = "/update/{menuId}", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(@PathVariable String menuId, SysMenu param) {
		SysMenuVo menu = sysMenuService.getByMenuId(menuId);
		Result ret = new Result();
		if (menu == null) {
			ret.addErr("菜单不存在");
		} else {
			if (StringUtils.isBlank(param.getName())) {
				ret.addErr("请输入菜单姓名");
			}
		}
		if (ret.checkForm()) {
			menu.setName(param.getName());
			menu.setType(param.getType());
			menu.setStatus(param.getStatus());
			menu.setExpand(param.getExpand());
			menu.setUrl(param.getUrl());
			menu.setIcon(param.getIcon());
			menu.setIconOpen(param.getIconOpen());
			menu.setRemark(param.getRemark());
			if (menu.getType().intValue() == 1) {
				if (StringUtils.isBlank(menu.getIcon())) {
					menu.setIcon("icon-folder");
				}
			} else {
				if (StringUtils.isBlank(menu.getIcon())) {
					menu.setIcon("icon-pict");
				}
			}

			sysMenuService.updateById(menu);
		}
		return ret;
	}

	/**
	 * 移动节点
	 * 
	 * @param targetId
	 *            目标节点id
	 * @param sourceId
	 *            源节点id
	 * @param point
	 *            操作类型 取值范围: append,top,bottom
	 */
	@RequestMapping(value = "/move", method = RequestMethod.POST)
	@ResponseBody
	public Result move(@RequestParam String targetId, @RequestParam String sourceId, @RequestParam String point) {
		Result ret = new Result();
		if (null == targetId || null == sourceId || null == point) {
			ret.addErr("参数不能为空");
		}
		if (ret.checkForm()) {
			int value = sysMenuService.move(targetId, sourceId, point);
			if (value == 0) {
				ret.addErr("叶子节点不允许追加子节点");
			}
		}
		return ret;
	}
	
	@RequestMapping(value = "/delete/{menuId}", method = RequestMethod.POST)
	@ResponseBody
   	public Result doDelete(@PathVariable String menuId) {
		Result ret = new Result();
		SysMenu sysMenu = new SysMenu();
		sysMenu.setMenuId(menuId);
		sysMenuService.delete(sysMenu);
   		return ret;
   	}
}
